<?php

namespace app\admin\controller\pms;

use app\admin\model\Reservation;
use app\admin\model\Pmsorderinfo;
use app\common\controller\Backend;
use app\common\model\Category;
use app\common\model\User;
use services\QCloudSmsService;
use think\Db;
use Overtrue\Pinyin\Pinyin;
use think\Model;

/**
 * 房态
 *
 * @icon fa fa-calendar
 */
class Pmsroomstatus extends Backend
{

    protected $prefix = '';
    protected $member = ['error' => 300];

    public $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model  = new Pmsorderinfo();
        $this->prefix = config('database.prefix');
    }


    /**
     * 查看
     */
    public function index()
    {
        $oi     = new \app\admin\model\Pmsorderinfo;
        $opl    = new \app\admin\model\Pmsorderpeoplelist;
        $rt     = new \app\admin\model\Pmsroomtype;
        $ri     = new \app\admin\model\Pmsroominfo;
        $resi   = new \app\admin\model\Pmsreserveinfo;

        $t          = input('t', '');
        $start_date = '';
        $end_date   = '';

        $room_all_count    = $ri->where('state', 1)->count();                                                     //全部房间数
        $room_full_count   = $oi->whereIn('order_status', [0,-1])->count();                            //有住人数
        $room_empty_count  = $ri->where('state', 1)->where('room_status', 0)->count();                            //空房数
        $room_dirty_count  = $ri->where('state', 1)->where('is_dirty', 1)->count();                               //脏房数
        $room_lock_count   = $ri->where('state', 1)->where('is_lock', 1)->count();                                //锁房数
        $room_repair_count = $ri->where('state', 1)->where('is_repair', 1)->count();                              //维修房数


        //获取楼层
        $riList = $ri->field('floor')->order('floor')->group('floor')->select();
        if (count($riList) > 0) {
            $where = [];
            switch ($t) {
                case 'room_full':
                    $where = ['room_status' => 1];
                    break;

                case 'room_reserve':
                    // $where       = ['id' => ['in', 0]];
                    $reserve_ids = [];
                    // foreach ($room_reserve_list as $rr) {
                    //     array_push($reserve_ids, $rr['room_info_id']);
                    // }
                    // if (count($reserve_ids) > 0) {
                    //     $where = ['id' => ['in', $reserve_ids]];
                    // }
                    break;

                case 'room_empty':
                    $where = ['room_status' => 0];
                    break;

                case 'room_dirty':
                    $where = ['is_dirty' => 1];
                    break;

                case 'room_repair':
                    $where = ['is_repair' => 1];
                    break;

                case 'room_lock':
                    $where = ['is_lock' => 1];
                    break;

                case 'search_room':
                    $search_dates = [];
                    $rooms_data   = [];
                    $start_date   = input('start_date', '');
                    $end_date     = input('end_date', '');

                    if ($start_date == $end_date) {
                        array_push($search_dates, $start_date);
                    } else {
                        for ($i = 0; $i < 99999; $i++) {
                            $the_date = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($start_date)));
                            array_push($search_dates, $the_date);

                            if ($the_date == date('Y-m-d', strtotime('-1 day', strtotime($end_date)))) {
                                break;
                            }
                        }
                    }

                    $oiRoomsList = $oi->field('id,room_info_id,check_in_time,check_out_time')
                        ->where(['check_out_time' => ['>=', strtotime(date('Y-m-d'))]])->where('order_status',0)->select();
                    foreach ($oiRoomsList as $item) {
                        $key = 'room_' . $item['room_info_id'];
                        if (!isset($rooms_data[$key])) {
                            $rooms_data[$key] = [];
                        }
                        if (date('Y-m-d', $item['check_in_time']) == date('Y-m-d', $item['check_out_time'])) {
                            array_push($rooms_data[$key], date('Y-m-d', $item['check_in_time']));
                        } else {
                            for ($d = 0; $d < 9999999; $d++) {
                                $the_date = date('Y-m-d', strtotime('+' . $d . ' day', $item['check_in_time']));
                                array_push($rooms_data[$key], $the_date);

                                if ($the_date == date('Y-m-d', strtotime('-1 day', $item['check_out_time']))) {
                                    break;
                                }
                            }
                        }
                    }
                    $resiRoomsList = $resi->field('id,room_info_id,check_in_time,check_out_time')->where(['check_out_time' => ['>=', strtotime(date('Y-m-d'))]])->where('reserve_status', 0)->select();
                    foreach ($resiRoomsList as $item) {
                        $key = 'room_' . $item['room_info_id'];
                        if (!isset($rooms_data[$key])) {
                            $rooms_data[$key] = [];
                        }
                        if (date('Y-m-d', $item['check_in_time']) == date('Y-m-d', $item['check_out_time'])) {
                            array_push($rooms_data[$key], date('Y-m-d', $item['check_in_time']));
                        } else {
                            for ($d = 0; $d < 9999999; $d++) {
                                $the_date = date('Y-m-d', strtotime('+' . $d . ' day', $item['check_in_time']));
                                array_push($rooms_data[$key], $the_date);

                                if ($the_date == date('Y-m-d', strtotime('-1 day', $item['check_out_time']))) {
                                    break;
                                }
                            }
                        }
                    }

                    $roomsIds  = [];
                    $roomsList = $ri->field('id')->where('state', 1)->select();
                    foreach ($roomsList as $item) {
                        $key = 'room_' . $item['id'];
                        if (isset($rooms_data[$key])) {
                            $is_exists = false;
                            foreach ($rooms_data[$key] as $rd) {
                                if (in_array($rd, $search_dates)) {
                                    $is_exists = true;
                                    break;
                                }
                            }

                            if (!$is_exists) {
                                array_push($roomsIds, $item['id']);
                            }
                        } else {
                            array_push($roomsIds, $item['id']);
                        }
                    }

                    $where = ['id' => ['in', $roomsIds]];

                    break;
            }
            foreach ($riList as $i => $item) {
                $riSubList = $ri->field('id,room_type,room_no,room_status,is_dirty,is_repair,is_lock')
                    ->where('floor', $item['floor'])
                    ->where($where)
                    ->where('state', 1)
                    ->order('room_no')
                    ->select();
                foreach ($riSubList as $j => $room) {
                    $m                               = $rt->where('id', $room['room_type'])->find();
                    $riSubList[$j]['room_type_name'] = $m ? $m['name'] : '';

                    $riSubList[$j]['check_in_time']  = '';
                    $riSubList[$j]['check_out_time'] = '';
                    $riSubList[$j]['customers']      = '';

                    $riSubList[$j]['order_id']     = 0;
                    $riSubList[$j]['deposit_flag'] = 0;  //0=不显示欠押金标识
                    $riSubList[$j]['deposit']      = 0;
                    // if ($room['room_status']) {
                    $oiModel = $oi->field('id,order_no,realname,check_in_time,check_out_time,days,deposit,order_status')
                        ->where('room_info_id', $room['id'])
                        ->whereIn('order_status', [0,-1])
                        ->order('check_in_time asc')
                        ->find();
                    if ($oiModel) {
                        // dump($oiModel->toArray());die;
                        $riSubList[$j]['room_status']    = 1;
                        $riSubList[$j]['order_id']       = $oiModel['id'];
                        $riSubList[$j]['check_in_time']  = date('Y/m/d', $oiModel['check_in_time']);
                        $riSubList[$j]['check_out_time'] = date('Y/m/d', $oiModel['check_out_time']);
                        $riSubList[$j]['deposit']        = $oiModel['deposit'];
                        $riSubList[$j]['stay_name']      = $oiModel['realname'];

                        $oplList = $opl->field('realname')
                            ->where('order_id', $oiModel['id'])
                            ->where('state', 0)
                            ->select();
                        foreach ($oplList as $p) {
                            $riSubList[$j]['customers'] .= $p['realname'] . '/';
                        }
                        $riSubList[$j]['customers'] = $riSubList[$j]['customers'] ? substr($riSubList[$j]['customers'], 0, strlen($riSubList[$j]['customers']) - 1) : '';

                        // 住院状态
                        $riSubList[$j]['order_status'] = $oiModel['order_status'];
                        // 是否超过出院时间
                        $riSubList[$j]['over_date'] = (int)(date('Y/m/d') >= date('Y/m/d', $oiModel['check_out_time']));
                    }


                    //房押金
                    /*if ($oiModel['deposit']) {
                        $pay_deposit = $op->where('order_id', $oiModel['id'])->where('pay_type', '收押金')->where('state', 0)->sum('money');

                        if ($pay_deposit < $oiModel['deposit']) {
                            $riSubList[$j]['deposit_flag'] = 1;
                        }
                    }*/
                    // }
                }
                // dump($riSubList->toArray());die;
                $riList[$i]['rooms'] = $riSubList;
            }
        }

        // die;
        $this->view->assign("t", $t);
        $this->view->assign("start_date", $start_date);
        $this->view->assign("end_date", $end_date);
        $this->view->assign("room_all_count", $room_all_count);
        $this->view->assign("room_empty_count", $room_empty_count);
        $this->view->assign("room_full_count", $room_full_count);
        $this->view->assign("room_reserve_count", 0);
        $this->view->assign("room_dirty_count", $room_dirty_count);
        $this->view->assign("room_lock_count", $room_lock_count);
        $this->view->assign("room_repair_count", $room_repair_count);
        $this->view->assign("riList", $riList);
        // dump($riList->toArray());die;
        return $this->view->fetch();
    }


    /**
     * 预定房间
     */
    public function reserve()
    {
        $conf                 = new \app\admin\model\Pmsconfig;
        $oi                   = new \app\admin\model\Pmsorderinfo;
        $ri                   = new \app\admin\model\Pmsroominfo;
        $rt                   = new \app\admin\model\Pmsroomtype;
        $resi                 = new \app\admin\model\Pmsreserveinfo;
        $rpl                  = new \app\admin\model\Pmsreservepeoplelist;
        $this->model          = new \app\admin\model\Pmsreserveinfo;
        $certificatestypeList = $conf->selectpage('certificates_type');
        $order_flag           = $conf->getvalue('order_flag');
        $sourceList           = $conf->selectpage('source');
        $nationList           = $conf->nation_list();
        $prefix               = $this->prefix;
        $py                   = new Pinyin();

        $id         = input('id', 0);
        $start_date = input('start_date', '');
        $end_date   = input('end_date', '');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (!$params['realname']) {
                    $this->error('患者姓名不能为空');
                }
                if (!$params['person_no']) {
                    $this->error('身份证不能为空');
                }
                if (!$params['tel']) {
                    $this->error('联系电话不能为空');
                }

                if (strtotime($params['check_in_time']) > strtotime($params['check_out_time'])) {
                    $this->error('住院时间大于出院时间');
                }

                $reserveDates = [];
                $oiModel      = $oi->field('id,check_in_time,check_out_time')
                    ->where('room_info_id', $params['room_info_id'])
                    ->where("order_status", 0)
                    ->find();
                if ($oiModel) {
                    $res_check_in_time  = date('Y-m-d', $oiModel['check_in_time']);
                    $res_check_out_time = date('Y-m-d', strtotime('-1 day', $oiModel['check_out_time']));
                    for ($i = 0; $i < 9999999; $i++) {
                        $reserveDateTemp = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($res_check_in_time)));
                        array_push($reserveDates, $reserveDateTemp);
                        if ($reserveDateTemp == $res_check_out_time) {
                            break;
                        }
                    }
                }

                $resiList = $resi->field('id,check_in_time,check_out_time')
                    ->where('room_info_id', $params['room_info_id'])
                    ->where("reserve_status", 0)
                    ->select();
                foreach ($resiList as $item) {
                    $res_check_in_time  = date('Y-m-d', $item['check_in_time']);
                    $res_check_out_time = date('Y-m-d', strtotime('-1 day', $item['check_out_time']));
                    for ($i = 0; $i < 9999999; $i++) {
                        $reserveDateTemp = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($res_check_in_time)));
                        array_push($reserveDates, $reserveDateTemp);
                        if ($reserveDateTemp == $res_check_out_time) {
                            break;
                        }
                    }
                }

                if (count($reserveDates)) {
                    $is_DateConflict = false;
                    $check_in_time   = date('Y-m-d', strtotime($params['check_in_time']));
                    $check_out_time  = date('Y-m-d', strtotime('-1 day', strtotime($params['check_out_time'])));
                    for ($i = 0; $i < 9999999; $i++) {
                        $TempDate = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($check_in_time)));
                        if (in_array($TempDate, $reserveDates)) {
                            $is_DateConflict = true;
                            break;
                        }
                        if ($TempDate == $check_out_time) {
                            break;
                        }
                    }
                    if ($is_DateConflict) {
                        $this->error('日期有冲突');
                    }
                }

                //获取房型的押金
                $roomtypeM         = $rt->where('id', $params['room_type_id'])->find();
                $params['deposit'] = $roomtypeM ? $roomtypeM['deposit'] : 0;

                $params['creator']        = $this->auth->id;
                $params['last_editor']    = $this->auth->id;
                $params['reserve_no']     = $this->model->create_reserve_no($order_flag);
                $params['birthday']       = strtotime($params['birthday']);
                $params['reserve_status'] = 0;

                $pinyinArray = $py->convert($params['realname']);
                $pinyin      = '';
                $sname       = '';
                foreach ($pinyinArray as $item) {
                    $pinyin .= $item;
                    $sname  .= ucwords(substr($item, 0, 1));
                }
                $params['pinyin'] = $pinyin;
                $params['sname']  = $sname;

                $customerJson = [];
                if ($params['customer_data']) {
                    $customer_dataJson = json_decode($params['customer_data'], true);
                    foreach ($customer_dataJson as $item) {
                        $pinyinArray = $py->convert($item['realname']);
                        $pinyin      = '';
                        $sname       = '';
                        foreach ($pinyinArray as $x) {
                            $pinyin .= $x;
                            $sname  .= ucwords(substr($x, 0, 1));
                        }

                        array_push($customerJson, [
                            'user_id'           => 0,
                            'realname'          => $item['realname'],
                            'sname'             => $sname,
                            'pinyin'            => $pinyin,
                            'sex'               => $item['sex'],
                            'certificates_type' => $item['certificates_type'],
                            'person_no'         => $item['person_no'],
                            'birthday'          => strtotime($item['birthday']),
                            'tel'               => $item['tel']
                        ]);
                    }
                } else {
                    array_push($customerJson, [
                        'user_id'           => 0,
                        'realname'          => $params['realname'],
                        'sname'             => $sname,
                        'pinyin'            => $pinyin,
                        'sex'               => $params['sex'],
                        'certificates_type' => $params['certificates_type'],
                        'person_no'         => $params['person_no'],
                        'birthday'          => strtotime($params['birthday']),
                        'tel'               => $params['tel']
                    ]);
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $reserveM = $this->model->where('reserve_no', $params['reserve_no'])->find();

                    $this->pri_add_user($reserveM['realname'], $reserveM['sex'], $reserveM['birthday'], $reserveM['tel'], $reserveM['certificates_type'], $reserveM['person_no']);

                    if (count($customerJson) > 0) {
                        foreach ($customerJson as $item) {

                            $rpl->insert([
                                'reserve_id'        => $reserveM['id'],
                                'user_id'           => $item['user_id'],
                                'realname'          => $item['realname'],
                                'sname'             => $item['sname'],
                                'pinyin'            => $item['pinyin'],
                                'sex'               => $item['sex'],
                                'certificates_type' => $item['certificates_type'],
                                'person_no'         => $item['person_no'],
                                'birthday'          => $item['birthday'],
                                'tel'               => $item['tel'],
                                'remarks'           => '',
                                'state'             => 0,
                                'createtime'        => time(),
                                'creator'           => $this->auth->id,
                                'updatetime'        => time(),
                                'last_editor'       => $this->auth->id
                            ]);

                            $this->pri_add_user($item['realname'], $item['sex'], $item['birthday'], $item['tel'], $item['certificates_type'], $item['person_no']);
                        }
                    }

                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $roomModel = null;
        if ($id) {
            $roomModel = $ri->alias('ri')
                ->field('ri.id as room_info_id,rt.id as room_type_id,ri.floor,rt.name,ri.room_no,rt.remarks')
                ->join($prefix . 'pms_room_type rt', 'ri.room_type = rt.id')
                ->where('ri.id', $id)
                ->find();
        } else {
            exit;
        }

        $this->view->assign("start_date", $start_date);
        $this->view->assign("end_date", $end_date);
        $this->view->assign("roomModel", $roomModel);
        $this->view->assign("certificatestypeList", $certificatestypeList);
        $this->view->assign("sourceList", $sourceList);
        $this->view->assign("nationList", $nationList);
        return $this->view->fetch();
    }

    /**
     * 订单详情
     */
    public function order_detail()
    {
        $a                     = new \app\admin\model\Admin;
        $conf                  = new \app\admin\model\Pmsconfig;
        $oi                    = new \app\admin\model\Pmsorderinfo;
        $opl                   = new \app\admin\model\Pmsorderpeoplelist;
        $ritems                = new \app\admin\model\Pmsroomitems;
        $servicesitems         = new \app\admin\model\Pmsservicesitems;
        $op                    = new \app\admin\model\Pmsorderpayment;
        $oroomitems            = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems        = new \app\admin\model\Pmsorderservicesitems;
        $certificatestypeList  = $conf->selectpage('certificates_type');
        $sourceList            = $conf->selectpage('source');
        $nationList            = $conf->nation_list();
        $roomitemsList         = $ritems->field('id,name,price')->where('state', 1)->select();
        $roomservicesitemsList = $servicesitems->field('id,name,price')->where('state', 1)->select();
        $prefix                = $this->prefix;
        $this->model           = new \app\admin\model\Pmsorderinfo;

        $id = input('id', 0);

        $oiModel = null;
        if (!$id) {
            $this->error('传递参数为空');
        }
        $oiModel = $oi->alias('oi')
            ->field('oi.*, ri.room_no,ri.floor,rt.name as room_type_name')
            ->join($prefix . 'pms_room_info ri', 'ri.id = oi.room_info_id')
            ->join($prefix . 'pms_room_type rt', 'rt.id = oi.room_type_id')
            ->where('oi.id', $id)
            ->find();

        if ($oiModel) {
            $oiModel['birthday_text']       = date('Y-m-d', $oiModel['birthday']);
            $oiModel['check_in_time_text']  = date('Y-m-d', $oiModel['check_in_time']);
            $oiModel['check_out_time_text'] = date('Y-m-d', $oiModel['check_out_time']);
            $oiModel['price_json_array']    = json_decode($oiModel['price_json'], true);

            //同住客人列表
            $oplList = $opl->field('realname,sex,certificates_type,person_no,birthday,tel')->where('order_id', $oiModel['id'])->where('state', 0)->select();
            foreach ($oplList as $i => $item) {
                $oplList[$i]['birthday'] = date('Y-m-d', $item['birthday']);
            }
            $oiModel['customer_data'] = $oplList;
        } else {
            $this->error('获取预定错误');
        }

        //收款/消费记录
        $pay_list          = ['rows' => [], 'total' => 0, 'total_diff' => 0, 'total_expenditure' => 0, 'total_income' => 0];
        $total_income      = 0;            //收入总计
        $total_expenditure = 0;            //支出总计

        //消费,房费
        $total_expenditure += $oiModel['total_price'];
        $m                 = $a->where('id', $oiModel['creator'])->find();
        $creator_nickname  = $m ? $m['nickname'] : '';
        array_push($pay_list['rows'], [
            'id'               => $oiModel['id'],
            'type'             => 'roomcost',
            'name'             => '消费：房费(' . date('m/d H:i', $oiModel['check_in_time']) . ' -- ' . date('m/d H:i', $oiModel['check_out_time']) . ')',
            'money'            => 0 - $oiModel['total_price'],
            'createtime'       => $oiModel['createtime'],
            'creator_nickname' => $creator_nickname,
            'remarks'          => $oiModel['remarks']
        ]);

        //消费,房间物品
        $oroomitemsList = $oroomitems->where('order_id', $oiModel['id'])->select();
        if (count($oroomitemsList)) {
            foreach ($oroomitemsList as $item) {
                $m                 = $a->where('id', $item['creator'])->find();
                $creator_nickname  = $m ? $m['nickname'] : '';
                $item_total_price  = $item['num'] * $item['price'];
                $total_expenditure += $item_total_price;

                array_push($pay_list['rows'], [
                    'id'               => $item['id'],
                    'type'             => 'roomitems',
                    'name'             => '消费：' . $item['name'] . ' X ' . $item['num'],
                    'money'            => 0 - $item_total_price,
                    'createtime'       => $item['createtime'],
                    'creator_nickname' => $creator_nickname,
                    'remarks'          => $item['remarks']
                ]);
            }
        }

        //消费,服务
        $oservicesitemsList = $oservicesitems->where('order_id', $oiModel['id'])->select();
        if (count($oservicesitemsList)) {
            foreach ($oservicesitemsList as $item) {
                $m                 = $a->where('id', $item['creator'])->find();
                $creator_nickname  = $m ? $m['nickname'] : '';
                $item_total_price  = $item['num'] * $item['price'];
                $total_expenditure += $item_total_price;

                array_push($pay_list['rows'], [
                    'id'               => $item['id'],
                    'type'             => 'servicesitems',
                    'name'             => '消费：' . $item['name'] . ' X ' . $item['num'],
                    'money'            => 0 - $item_total_price,
                    'createtime'       => $item['createtime'],
                    'creator_nickname' => $creator_nickname,
                    'remarks'          => $item['remarks']
                ]);
            }
        }

        //收款
        $opList = $op->where('order_id', $oiModel['id'])->where('state', 0)->select();
        if (count($opList)) {
            foreach ($opList as $item) {
                $m                = $a->where('id', $item['creator'])->find();
                $creator_nickname = $m ? $m['nickname'] : '';
                $total_income     += $item['money'];

                array_push($pay_list['rows'], [
                    'id'               => $item['id'],
                    'type'             => 'payment',
                    'name'             => $item['pay_type'],
                    'money'            => $item['money'],
                    'createtime'       => $item['createtime'],
                    'creator_nickname' => $creator_nickname,
                    'remarks'          => $item['remarks']
                ]);
            }
        }

        //收支平衡
        $total_diff                    = 0 - $total_expenditure + $total_income;
        $pay_list['total_expenditure'] = 0 - $total_expenditure;
        $pay_list['total_income']      = $total_income;
        $pay_list['total_diff']        = $total_diff;

        $room = (new \app\admin\model\Pmsroominfo())->queryBookableRoomsByDate($oiModel['check_in_time'], $oiModel['check_out_time']);

        foreach ($room as &$item) {
            $item['room_info'] = $item['id'] . ',' . $item['room_type'];
        }
        unset($item);
        $oiModel['room_info'] = $oiModel['room_info_id'] . ',' . $oiModel['room_type_id'];

        $this->assign('roomList', $room);
        // halt($oiModel->toArray());
        $oiModel['age'] = get_date(date('Y-m-d', $oiModel['birthday']));
        $this->assign("oiModel", $oiModel);

        $diseaseCate          = (new Category())->field('id,name,type,flag')->where(['pid' => 14])->select()->toArray();
        $diseaseId            = $oiModel['disease_id'];
        foreach ($diseaseCate as $item) {
            if ($item['id'] == $diseaseId) {
                $oiModel['disease_cate'] = $item['name'];
            }
        }
        $this->assign("category", $diseaseCate);

        $this->assign("sourceList", $sourceList);
        $this->assign("nationList", $nationList);
        $this->assign("certificatestypeList", $certificatestypeList);
        $this->assign("roomitemsList", $roomitemsList);
        $this->assign("roomservicesitemsList", $roomservicesitemsList);
        $this->assign("pay_list", $pay_list);

        $this->assign("end_date", date('Y-m-d'));
        return $this->view->fetch();
    }

    /**
     * 预定详情
     */
    public function reserve_detail()
    {
        $conf                 = new \app\admin\model\Pmsconfig;
        $resi                 = new \app\admin\model\Pmsreserveinfo;
        $rpl                  = new \app\admin\model\Pmsreservepeoplelist;
        $this->model          = new \app\admin\model\Pmsreserveinfo;
        $certificatestypeList = $conf->selectpage('certificates_type');
        $sourceList           = $conf->selectpage('source');
        $nationList           = $conf->nation_list();
        $prefix               = $this->prefix;
        $id                   = input('id', 0);
        $resiModel            = null;
        if ($id) {
            $resiModel = $resi->alias('resi')
                ->field('resi.*, ri.room_no,ri.floor,rt.name as room_type_name')
                ->join($prefix . 'pms_room_info ri', 'ri.id = resi.room_info_id')
                ->join($prefix . 'pms_room_type rt', 'rt.id = resi.room_type_id')
                ->where('resi.id', $id)
                ->find();

            if ($resiModel) {
                $resiModel['birthday_text']       = date('Y-m-d', $resiModel['birthday']);
                $resiModel['check_in_time_text']  = date('Y-m-d H:i:s', $resiModel['check_in_time']);
                $resiModel['check_out_time_text'] = date('Y-m-d H:i:s', $resiModel['check_out_time']);
                $resiModel['price_json_array']    = json_decode($resiModel['price_json'], true);

                //同住客人列表
                $rplList = $rpl->field('realname,sex,certificates_type,person_no,birthday,tel')->where('reserve_id', $resiModel['id'])->where('state', 0)->select();
                foreach ($rplList as $i => $item) {
                    $rplList[$i]['birthday'] = date('Y-m-d', $item['birthday']);
                }
                $resiModel['customer_data'] = $rplList;
            } else {
                $this->error('获取预定错误');
            }
        } else {
            $this->error('传递参数为空');
        }

        $this->view->assign("resiModel", $resiModel);
        $this->view->assign("sourceList", $sourceList);
        $this->view->assign("nationList", $nationList);
        $this->view->assign("certificatestypeList", $certificatestypeList);
        return $this->view->fetch();
    }


    /**
     * 散客入住
     */
    public function checkin()
    {
        $conf                 = new \app\admin\model\Pmsconfig;
        $ri                   = new \app\admin\model\Pmsroominfo;
        $certificatestypeList = $conf->selectpage('certificates_type');
        $sourceList           = $conf->selectpage('source');
        $nationList           = $conf->nation_list();
        $prefix               = $this->prefix;

        $id         = input('id', 0);
        $start_date = input('start_date', '');
        $end_date   = input('end_date', '');

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (!$params['patient_name']) {
                    $this->error('患者姓名不能为空');
                }
                if (!$params['patient_cardno']) {
                    $this->error('身份证不能为空');
                }

                if (strtotime($params['stay_date']) === strtotime($params['out_date'])) {
                    $this->error('不能在同一天办理住院出院');
                }
                if (strtotime($params['stay_date']) > strtotime($params['out_date'])) {
                    $this->error('出院时间不能小于住院时间');
                }

                Db::startTrans();
                try {
                    (new Reservation())->changeOrder($params + ['id_sk' => 1, 'source' => '现场预约'], $this->auth->id);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error(__($e->getMessage()));
                }
                $this->success('预定成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (!$id) {
            $this->error('无效床位！');
        }
        $roomModel = $ri->alias('ri')
            ->field('ri.id as room_info_id,rt.id as room_type_id,ri.floor,rt.name,ri.room_no,rt.remarks')
            ->join($prefix . 'pms_room_type rt', 'ri.room_type = rt.id')
            ->where('ri.id', $id)
            ->find();

        $this->view->assign("start_date", $start_date);
        $this->view->assign("end_date", $end_date);
        $this->view->assign("roomModel", $roomModel);
        $this->view->assign("reserve_id", 0);
        $this->view->assign("certificatestypeList", $certificatestypeList);
        $this->view->assign("sourceList", $sourceList);
        $this->view->assign("nationList", $nationList);

        $this->assign("category", (new Category())->field('id,name,type,flag')->where(['pid' => 14])->select());
        return $this->view->fetch();
    }

    /**
     * 房态日历
     */
    public function calendar()
    {
        $room_id = input('id', 0);

        $this->view->assign("room_id", $room_id);
        return $this->view->fetch();
    }

    /**
     * 收款
     */
    public function pay()
    {
        $conf         = new \app\admin\model\Pmsconfig;
        $pay_typeList = $conf->selectpage('pay_type');
        $oi           = new \app\admin\model\Pmsorderinfo;
        $opl          = new \app\admin\model\Pmsorderpeoplelist;
        $this->model  = new \app\admin\model\Pmsorderpayment;

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params                = $this->preExcludeFields($params);
                $params['creator']     = $this->auth->id;
                $params['last_editor'] = $this->auth->id;
                $params['state']       = 0;

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $room_id = input('id', 0);
        $oiModel = $oi->where('room_info_id', $room_id)->whereIn('order_status', [0,-1])->find();
        if ($oiModel) {
            $oiModel['total_price']         = number_format($oiModel['total_price']);
            $oiModel['check_in_time_text']  = date('Y/m/d H:i', $oiModel['check_in_time']);
            $oiModel['check_out_time_text'] = date('Y/m/d H:i', $oiModel['check_out_time']);
            $oiModel['pay_total_price']     = $this->model->where('order_id', $oiModel['id'])->where('state', 0)->sum('money');

            $oplList = $opl->field('id,realname')->where('order_id', $oiModel['id'])->where('state', 0)->select();
            $peoples = '';
            foreach ($oplList as $item) {
                $peoples .= $item['realname'] . '/';
            }
            $peoples            = substr($peoples, 0, strlen($peoples) - 1);
            $oiModel['peoples'] = $peoples;
        } else {
            echo 'error 100';
            exit;
        }

        $this->view->assign("room_id", $room_id);
        $this->view->assign("oiModel", $oiModel);
        $this->view->assign("pay_typeList", $pay_typeList);
        return $this->view->fetch();
    }

    /**
     * 出院
     */
    public function checkout()
    {
        $op     = new \app\admin\model\Pmsorderpayment;
        $opl    = new \app\admin\model\Pmsorderpeoplelist;
        $oi     = new \app\admin\model\Pmsorderinfo;
        $ri     = new \app\admin\model\Pmsroominfo;
        $prefix = $this->prefix;

        $order_id = input('id', 0);
        $oiModel = $oi->where('id', $order_id)->whereIn('order_status', [0,-1])->find();
        if ($oiModel) {
            $riModel = $ri->alias('ri')
                ->field('ri.id,rt.name,ri.room_no')
                ->join($prefix . 'pms_room_type rt', 'ri.room_type = rt.id')
                ->where('ri.id', $oiModel->room_info_id)
                ->find();

            $oiModel['room_type_name']      = $riModel['name'];
            $oiModel['room_no']             = $riModel['room_no'];
            $oiModel['total_price']         = number_format($oiModel['total_price']);
            $oiModel['check_in_time_text']  = date('Y/m/d H:i', $oiModel['check_in_time']);
            $oiModel['check_out_time_text'] = date('Y/m/d H:i', $oiModel['check_out_time']);
            $oiModel['pay_total_price']     = $op->where('order_id', $oiModel['id'])->where('state', 0)->sum('money');
            $oiModel['age']                 = get_date($oiModel['birthday']);

            $oplList = $opl->field('id,realname,tel')->where('order_id', $oiModel['id'])->where('state', 0)->select();
            $peoples = '';
            foreach ($oplList as $item) {
                $peoples        .= $item['realname'] . '/';
                $oiModel['tel'] = $item['tel'];
            }
            $peoples            = substr($peoples, 0, strlen($peoples) - 1);
            $oiModel['peoples'] = $peoples;
        } else {
            echo 'error 100';
            exit;
        }

        $this->view->assign("room_id", $oiModel->room_info_id);
        $this->view->assign("oiModel", $oiModel);
        return $this->view->fetch();
    }


    /**
     * Ajax设置房态
     */
    public function ajax_set_room()
    {
        $ri = new \app\admin\model\Pmsroominfo;

        $id     = input('id', 0);
        $status = input('status', '');

        if ($id && $status) {
            $m = $ri->where('id', $id)->find();
            if ($m) {
                $data = [];
                switch ($status) {
                    case 'lock':
                        $data['is_lock'] = 1;
                        break;
                    case 'unlock':
                        $data['is_lock'] = 0;
                        break;
                    case 'clean':
                        $data['is_dirty'] = 0;
                        break;
                    case 'dirty':
                        $data['is_dirty'] = 1;
                        break;
                    case 'repair':
                        $data['is_repair'] = 1;
                        break;
                    case 'repaired':
                        $data['is_repair'] = 0;
                        break;
                }
                $ri->where('id', $id)->update($data);

                $this->success('设置成功');
            } else {
                $this->error('错误，没有这个房间');
            }
        } else {
            $this->error('错误，请传参');
        }
    }

    /**
     * Ajax获取房价列表
     */
    public function ajax_get_room_price_list()
    {
        $ri     = new \app\admin\model\Pmsroominfo;
        $prefix = $this->prefix;

        $room_id        = input('room_id', 0);
        $check_in_time  = date('Y-m-d', strtotime(input('check_in_time', '')));
        $check_out_time = date('Y-m-d', strtotime(input('check_out_time', '')));

        if ($room_id && strtotime($check_in_time) && strtotime($check_out_time) && strtotime($check_out_time) >= strtotime($check_in_time)) {
            $sum_price = 0;
            $rows      = $ri->get_room_price_list($prefix, $room_id, $check_in_time, date('Y-m-d', strtotime('-1 day', strtotime($check_out_time))));

            foreach ($rows as $item) {
                $sum_price += $item['price'];
            }

            $this->member['error']            = 200;
            $this->member['total']            = count($rows);
            $this->member['rows']             = $rows;
            $this->member['sum_price']        = $sum_price;
            $this->member['sum_price_format'] = number_format($sum_price);
        }

        return json($this->member);
    }

    /**
     * 日历Ajax：获取房态日历
     */
    public function ajax_get_room_status_calendar()
    {
        $resi = new \app\admin\model\Reservation();
        $oi   = new \app\admin\model\Pmsorderinfo;

        $room_id    = input('room_id', 0);
        $flagconfig = ['success', 'info', 'warning'];
        $re         = [
            'success' => 1,
            'result'  => []
        ];

        if ($room_id) {
            $rows = [];

            //订单的
            $m = $oi->field('id,order_no as reserve_no, realname, check_in_time, check_out_time,room_info_id')
                ->where('room_info_id', $room_id)
                ->whereIn('order_status', [0,-1])
                ->select();

            if (!$m->isEmpty()) {
                foreach ($m as $val) {
                    $check_in_date_format  = date('Y-m-d', $val['check_in_time']);
                    $check_out_date_format = date('Y-m-d', strtotime('-1 day', $val['check_out_time']));

                    $val['title'] = '###';
                    $val['url']   = '###';
                    $val['class'] = 'event-info';
                    $val['start'] = strtotime($check_in_date_format . '00:00:00') . '000';
                    $val['end']   = strtotime($check_out_date_format . '23:59:59') . '000';
                    $val['flag']  = 'danger';
                    $val['type']  = 'order';

                    array_push($rows, $val->toArray());
                }

            }

            // dump($rows);die;
            //预定的
            /*$list = $resi->field('id, patient_name,stay_date,over_date')
                ->where('room_info_id', $room_id)
                ->where('status', 1)
                ->order('stay_date desc')
                ->select();

            if (count($list) > 0) {
                foreach ($list as $i => $item) {
                    // $check_in_date_format  = date('Y-m-d', $item['check_in_time']);
                    // $check_out_date_format = date('Y-m-d', strtotime('-1 day', $item['check_out_time']));
                    $list[$i]['title'] = '###';
                    $list[$i]['url']   = '###';
                    $list[$i]['class'] = 'event-info';
                    $list[$i]['start'] = $item['stay_date'];
                    $list[$i]['end']   = $item['over_date'];

                    $index            = $i % count($flagconfig);
                    $list[$i]['flag'] = $flagconfig[$index];
                    $list[$i]['type'] = 'reserve';

                    array_push($rows, $list[$i]);
                }
            }*/
            $re['result']  = $rows;
            $re['success'] = 1;
        }

        return json($re);
    }

    /**
     * 日历Ajax：获取房态详情
     */
    public function ajax_get_room_status_info()
    {
        $oi   = new \app\admin\model\Pmsorderinfo;
        $resi = new \app\admin\model\Pmsreserveinfo;
        $opl  = new \app\admin\model\Pmsorderpeoplelist;
        $rpl  = new \app\admin\model\Pmsreservepeoplelist;

        $type = input('type', 'order');
        $id   = input('id', 0);

        if ($type == 'reserve') {
            $m = $resi->field('id,reserve_no as no,realname,sex,tel,check_in_time,check_out_time,days,room_type_id,room_info_id,remarks')->where('id', $id)->find();

            if ($m) {
                $m['check_in_time_text']  = date('Y-m-d', $m['check_in_time']);
                $m['check_out_time_text'] = date('Y-m-d', $m['check_out_time']);

                $customersList  = $rpl->field('id,realname,tel,sex')->where('reserve_id', $m['id'])->where('state', 0)->select();
                $m['customers'] = $customersList;
                $m['type']      = $type;

                $this->member['error'] = 200;
                $this->member['row']   = $m;
            }
        } else {
            $m = $oi->field('id,order_no as no,realname,sex,tel,check_in_time,check_out_time,days,room_type_id,room_info_id,remarks')->where('id', $id)->find();

            if ($m) {
                $m['check_in_time_text']  = date('Y-m-d', $m['check_in_time']);
                $m['check_out_time_text'] = date('Y-m-d', $m['check_out_time']);

                $customersList  = $opl->field('id,realname,sex,tel')->where('order_id', $m['id'])->where('state', 0)->select();
                $m['customers'] = $customersList;
                $m['type']      = $type;

                $this->member['error'] = 200;
                $this->member['row']   = $m;
            }
        }
        return json($this->member);
    }

    /**
     * Ajax获取支付列表
     */
    public function ajax_get_order_payment()
    {
        $op = new \app\admin\model\Pmsorderpayment;

        $order_id = input('order_id', 0);

        $rows = [];
        if ($order_id) {
            $rows = $op->where('order_id', $order_id)->order('id desc')->select();
        }

        return json(['rows' => $rows, 'total' => count($rows)]);
    }

    /**
     * Ajax提交支付作废
     */
    public function ajax_cancel_payment()
    {
        $op = new \app\admin\model\Pmsorderpayment;

        $id      = input('id', 0);
        $remarks = input('remarks', '');

        if ($id && $remarks) {
            $m = $op->field('id,state,remarks')->where('id', $id)->find();
            if ($m) {
                $remarks = $m['remarks'] . '---【作废】' . $remarks;

                $op->where('id', $id)->update([
                    'state'   => 2,
                    'remarks' => $remarks
                ]);
                $this->success('提交成功');
            } else {
                $this->error('提交错误 101');
            }
        } else {
            $this->error('提交错误 100');
        }
    }

    /**
     * Ajax提交出院
     */
    public function ajax_checkout()
    {
        $oi = new \app\admin\model\Pmsorderinfo;

        $order_id = input('order_id', 0);

        if ($order_id) {
            $oiModel = $oi->where('id', $order_id)->where('order_status', 0)->find();

            if ($oiModel) {
                $oiModel->order_status   = 1;
                $oiModel->check_out_time = time();
                $oiModel->save();
                (new User())->where('id', $oiModel->uid)->setInc('hospitalization_count', 1);
                $this->success('出院成功');
            } else {
                $this->error('此订单已出院或还没住院，无法办理出院！');
            }
        } else {
            $this->error('参数错误');
        }
    }

    /**
     * Ajax出院操作：获取项目列表
     */
    public function ajax_get_project()
    {
        $oi             = new \app\admin\model\Pmsorderinfo;
        $op             = new \app\admin\model\Pmsorderpayment;
        $oroomitems     = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems = new \app\admin\model\Pmsorderservicesitems;
        $a              = new \app\admin\model\Admin;

        $order_id = input('order_id', 0);

        $rows              = [];
        $total_income      = 0;            //收入总计
        $total_expenditure = 0;            //支出总计
        $total_diff        = 0;            //收支平衡

        //房费
        $oiModel = $oi->where('id', $order_id)->whereIn('order_status', [0,-1])->find();
        if ($oiModel) {
            $check_in_time_text  = date('m/d H:i', $oiModel['check_in_time']);
            $check_out_time_text = date('m/d H:i', $oiModel['check_out_time']);
            $m                   = $a->where('id', $oiModel['creator'])->find();
            $creator_nickname    = $m ? $m['nickname'] : '';

            array_push($rows, [
                'name'             => '消费：房费(' . $check_in_time_text . ' -- ' . $check_out_time_text . ')',
                'money'            => 0 - $oiModel['total_price'],
                'createtime'       => $oiModel['createtime'],
                'creator_nickname' => $creator_nickname
            ]);

            $total_expenditure += $oiModel['total_price'];
        } else {
            return json([
                'rows'              => $rows,
                'total'             => count($rows),
                'total_income'      => $total_income,
                'total_expenditure' => $total_expenditure,
                'total_diff'        => $total_diff
            ]);
        }

        //消费,房间物品
        $oroomitemsList = $oroomitems->where('order_id', $oiModel['id'])->select();
        if (count($oroomitemsList)) {
            foreach ($oroomitemsList as $item) {
                $m                 = $a->where('id', $item['creator'])->find();
                $creator_nickname  = $m ? $m['nickname'] : '';
                $item_total_price  = $item['num'] * $item['price'];
                $total_expenditure += $item_total_price;

                array_push($rows, [
                    'name'             => '消费：' . $item['name'] . ' X ' . $item['num'],
                    'money'            => 0 - $item_total_price,
                    'createtime'       => $item['createtime'],
                    'creator_nickname' => $creator_nickname
                ]);
            }
        }

        //消费,服务
        $oservicesitemsList = $oservicesitems->where('order_id', $oiModel['id'])->select();
        if (count($oservicesitemsList)) {
            foreach ($oservicesitemsList as $item) {
                $m                 = $a->where('id', $item['creator'])->find();
                $creator_nickname  = $m ? $m['nickname'] : '';
                $item_total_price  = $item['num'] * $item['price'];
                $total_expenditure += $item_total_price;

                array_push($rows, [
                    'name'             => '消费：' . $item['name'] . ' X ' . $item['num'],
                    'money'            => 0 - $item_total_price,
                    'createtime'       => $item['createtime'],
                    'creator_nickname' => $creator_nickname
                ]);
            }
        }


        //收款
        $opList = $op->where('order_id', $oiModel['id'])->where('state', 0)->select();
        foreach ($opList as $i => $item) {
            $m                = $a->where('id', $item['creator'])->find();
            $creator_nickname = $m ? $m['nickname'] : '';

            $money = 0 + $item['money'];
            $name  = $item['remarks'] ? $item['pay_type'] . '(' . $item['remarks'] . ')' : $item['pay_type'];
            array_push($rows, [
                'name'             => $name,
                'money'            => $money,
                'createtime'       => $item['createtime'],
                'creator_nickname' => $creator_nickname
            ]);

            $total_income += $money;
        }

        $total_diff = 0 - $total_expenditure + $total_income;

        return json([
            'rows'              => $rows,
            'total'             => count($rows),
            'total_income'      => $total_income,
            'total_expenditure' => 0 - $total_expenditure,
            'total_diff'        => $total_diff
        ]);
    }

    /**
     * Ajax修改订单信息
     */
    public function ajax_update_order_info()
    {
        $oi             = new \app\admin\model\Pmsorderinfo;
        $opl            = new \app\admin\model\Pmsorderpeoplelist;
        $ri             = new \app\admin\model\Pmsroominfo;
        $el             = new \app\admin\model\Pmseventlogs;
        $oritems        = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems = new \app\admin\model\Pmsorderservicesitems;
        $py             = new Pinyin();

        $event   = input('event', '');
        $id      = input('id', 0);
        $remarks = input('order_invalid_memo', '');

        if (!$remarks) {
            $this->error('请输入理由');
        }
        $m        = $oi->where('id', $id)->find();
        $order_no = $m['order_no'];

        if ($m) {
            switch ($event) {
                case 'delete-roomitems':
                    $items_id = input('items_id', 0);
                    $m        = $oritems->where('id', $items_id)->find();
                    $oritems->where('id', $items_id)->delete();
                    $res_type = 'order';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '删除消费：' . $m['name'] . ' X ' . $m['num'] . ', 理由:' . $remarks
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail, 320),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->pri_get_gmv($id);
                    $this->success();
                    break;

                case 'edit-room':
                    $roomTypeId = input('room_type_id', '');
                    $roomInfoId = input('room_info_id', '');

                    $stayTime = strtotime(input('check_in_time'));
                    $liveTime = strtotime(input('check_out_time'));
                    $roomList = [['id' => $roomInfoId, 'room_type' => $roomTypeId]];
                    try {
                        (new Reservation())->checkStayRoom($roomList, $stayTime, $liveTime);
                    } catch (\Exception $e) {
                        $this->error($e->getMessage());
                    }
                    $oi->where('id', $id)->update([
                        'room_type_id'       => $roomTypeId,
                        'room_info_id'       => $roomInfoId,
                        'order_invalid_memo' => $remarks
                    ]);
                    $el->insert([
                        'res_type'   => 'order',
                        'res_id'     => $id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode(['description' => $this->auth->nickname . '更换床位：' . input('room_info_text', ''), '理由:' . $remarks], 320),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'delete-servicesitems':
                    $items_id = input('items_id', 0);
                    $m        = $oservicesitems->where('id', $items_id)->find();
                    $oservicesitems->where('id', $items_id)->delete();
                    $res_type = 'order';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '删除消费：' . $m['name'] . ' X ' . $m['num'] . ', 理由:' . $remarks
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail, 320),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->pri_get_gmv($id);
                    $this->success();
                    break;

                case 'edit-linkman':
                    $realname    = input('realname', '');
                    $pinyinArray = $py->convert($realname);
                    $pinyin      = '';
                    $sname       = '';
                    foreach ($pinyinArray as $item) {
                        $pinyin .= $item;
                        $sname  .= ucwords(substr($item, 0, 1));
                    }

                    $oi->where('id', $id)->update([
                        'disease_id'         => input('disease_id', ''),
                        'sex'                => input('sex', 0),
                        'realname'           => $realname,
                        'pinyin'             => $pinyin,
                        'sname'              => $sname,
                        'certificates_type'  => input('certificates_type', ''),
                        'person_no'          => input('person_no', ''),
                        'birthday'           => strtotime(input('birthday', 0)),
                        'nation'             => input('nation', ''),
                        'tel'                => input('tel', ''),
                        'remarks'            => input('order_remarks', ''),
                        'order_invalid_memo' => $remarks
                    ]);

                    $this->pri_add_user($realname, input('sex', 0), strtotime(input('birthday', 0)), input('tel', ''), input('certificates_type', ''), input('person_no', ''));

                    $res_type = 'order';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '修改患者信息, 理由:' . $remarks,
                        'old'         => [
                            'source'            => $m['source'],
                            'sex'               => $m['sex'],
                            'realname'          => $m['realname'],
                            'certificates_type' => $m['certificates_type'],
                            'person_no'         => $m['person_no'],
                            'birthday'          => $m['birthday'],
                            'tel'               => $m['tel'],
                            'remarks'           => $m['remarks']
                        ],
                        'new'         => [
                            'source'            => input('source', ''),
                            'sex'               => input('sex', 0),
                            'realname'          => input('realname', ''),
                            'certificates_type' => input('certificates_type', ''),
                            'person_no'         => input('person_no', ''),
                            'birthday'          => strtotime(input('birthday', 0)),
                            'tel'               => input('tel', ''),
                            'remarks'           => input('order_remarks', '')
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail, 320),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-date':
                    $check_in_time      = input('check_in_time', 0);
                    $check_in_time_int  = strtotime(date('Y-m-d', strtotime($check_in_time)));
                    $check_out_time     = input('check_out_time', 0);
                    $check_out_time_int = strtotime(date('Y-m-d', strtotime($check_out_time)));;

                    if (!($check_in_time_int && $check_out_time_int) || $check_in_time_int > $check_out_time_int) {
                        $this->error('时间格式不正确');
                    }
                    $days = (int)abs(($check_out_time_int - $check_in_time_int) / 86400);

                    // $total_price = 0;
                    /*$price_json  = $ri->get_room_price_list($prefix, $m['room_info_id'], $check_in_time, date('Y-m-d', strtotime('-1 day', $check_out_time_int)));

                    foreach ($price_json as $item) {
                        $total_price += $item['price'];
                    }*/

                    $oi->where('id', $id)->update([
                        'check_in_time'  => strtotime($check_in_time),
                        'check_out_time' => strtotime($check_out_time),
                        'days'           => $days,
                        'price_json'     => json_encode([]),
                        'total_price'    => 0
                    ]);

                    $res_type = 'order';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '修改入住信息, 理由:' . $remarks,
                        'old'         => [
                            'check_in_time'  => date('Y-m-d H:i:s', $m['check_in_time']),
                            'check_out_time' => date('Y-m-d H:i:s', $m['check_out_time']),
                            'days'           => $m['days'],
                            'price_json'     => json_decode($m['price_json'], true),
                            'total_price'    => $m['total_price']
                        ],
                        'new'         => [
                            'check_in_time'  => $check_in_time,
                            'check_out_time' => $check_out_time,
                            'days'           => $days,
                            'price_json'     => [],
                            'total_price'    => 0
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);

                    // 发送通知用户短信
                    //QCloudSmsService::create($m['tel'])->sendChangeDateSms(date('Y-m-d H:i:s', $m['check_in_time']), $check_in_time);
                    $this->success();
                    break;

                case 'edit-addons':
                    $oi->where('id', $id)->update([
                        'addons' => input('addons', '')
                    ]);

                    $res_type = 'order';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '修改附件, 理由:' . $remarks,
                        'old'         => [
                            'addons' => $m['addons']
                        ],
                        'new'         => [
                            'addons' => input('addons', '')
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $order_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-customer':
                    $customerJson = [];
                    if (input('customer_data', '')) {
                        $customer_dataJson = json_decode(input('customer_data', ''), true);
                        foreach ($customer_dataJson as $item) {
                            $pinyinArray = $py->convert($item['realname']);
                            $pinyin      = '';
                            $sname       = '';
                            foreach ($pinyinArray as $x) {
                                $pinyin .= $x;
                                $sname  .= ucwords(substr($x, 0, 1));
                            }

                            array_push($customerJson, [
                                'user_id'           => 0,
                                'realname'          => $item['realname'],
                                'sname'             => $sname,
                                'pinyin'            => $pinyin,
                                'sex'               => $item['sex'],
                                'certificates_type' => $item['certificates_type'],
                                'person_no'         => $item['person_no'],
                                'birthday'          => strtotime($item['birthday']),
                                'tel'               => $item['tel']
                            ]);
                        }
                    }


                    $oplList = $opl->field('user_id,realname,sname,pinyin,sex,certificates_type,person_no,birthday,tel')->where('order_id', $id)->where('state', 0)->select();

                    if (count($customerJson) > 0) {
                        $opl->where('order_id', $id)->update([
                            'state' => -1
                        ]);
                        foreach ($customerJson as $item) {
                            $opl->insert([
                                'order_id'          => $m['id'],
                                'user_id'           => $item['user_id'],
                                'realname'          => $item['realname'],
                                'sname'             => $item['sname'],
                                'pinyin'            => $item['pinyin'],
                                'sex'               => $item['sex'],
                                'certificates_type' => $item['certificates_type'],
                                'person_no'         => $item['person_no'],
                                'birthday'          => $item['birthday'],
                                'tel'               => $item['tel'],
                                'remarks'           => '',
                                'state'             => 0,
                                'createtime'        => time(),
                                'creator'           => $this->auth->id,
                                'updatetime'        => time(),
                                'last_editor'       => $this->auth->id
                            ]);

                            $this->pri_add_user($item['realname'], $item['sex'], $item['birthday'], $item['tel'], $item['certificates_type'], $item['person_no']);
                        }

                        $res_type = 'order';
                        $res_id   = $id;
                        $detail   = [
                            'description' => $this->auth->nickname . '修改同住客人, 理由:' . $remarks,
                            'old'         => [
                                'list' => $oplList
                            ],
                            'new'         => [
                                'list' => $customerJson
                            ]
                        ];
                        $el->insert([
                            'res_type'   => $res_type,
                            'res_id'     => $res_id,
                            'res_no'     => $order_no,
                            'event_type' => $event,
                            'detail'     => json_encode($detail),
                            'state'      => 0,
                            'createtime' => time(),
                            'creator'    => $this->auth->id
                        ]);
                    }
                    $this->success();
                    break;
            }
        } else {
            $this->error('订单不存在');
        }
    }

    /**
     * Ajax增加消费记录
     */
    public function ajax_add_order_items()
    {
        $ritems         = new \app\admin\model\Pmsroomitems;
        $servicesitems  = new \app\admin\model\Pmsservicesitems;
        $oritems        = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems = new \app\admin\model\Pmsorderservicesitems;

        $order_id = input('order_id', 0);
        $type     = input('type', '');
        $items_id = input('items_id', 0);
        $num      = input('num', 1);
        $addons   = input('addons', '');
        $remarks  = input('remarks', '');

        if ($order_id && $type && $items_id) {
            switch ($type) {
                case 'items':
                    $m = $ritems->where('id', $items_id)->find();
                    $oritems->insert([
                        'order_id'    => $order_id,
                        'items_id'    => $items_id,
                        'name'        => $m['name'],
                        'price'       => $m['price'],
                        'num'         => $num,
                        'addons'      => $addons,
                        'remarks'     => $remarks,
                        'createtime'  => time(),
                        'creator'     => $this->auth->id,
                        'updatetime'  => time(),
                        'last_editor' => $this->auth->id
                    ]);
                    break;
                case 'services':
                    $m = $servicesitems->where('id', $items_id)->find();
                    $oservicesitems->insert([
                        'order_id'          => $order_id,
                        'services_items_id' => $items_id,
                        'name'              => $m['name'],
                        'price'             => $m['price'],
                        'num'               => $num,
                        'addons'            => $addons,
                        'remarks'           => $remarks,
                        'createtime'        => time(),
                        'creator'           => $this->auth->id,
                        'updatetime'        => time(),
                        'last_editor'       => $this->auth->id
                    ]);
                    break;
            }
            $this->pri_get_gmv($order_id);

            $this->success();
        } else {
            $this->error('系统操作错误');
        }
    }

    /**
     * Ajax修改预定信息
     */
    public function ajax_update_reserve_info()
    {
        $oi     = new \app\admin\model\Pmsorderinfo;
        $resi   = new \app\admin\model\Pmsreserveinfo;
        $rpl    = new \app\admin\model\Pmsreservepeoplelist;
        $ri     = new \app\admin\model\Pmsroominfo;
        $el     = new \app\admin\model\Pmseventlogs;
        $prefix = $this->prefix;
        $py     = new Pinyin();

        $event   = input('event', '');
        $id      = input('id', 0);
        $remarks = input('remarks', '');

        if (!$remarks) {
            $this->error('请输入理由');
        }
        $m          = $resi->where('id', $id)->find();
        $reserve_no = $m['reserve_no'];

        if ($m) {
            switch ($event) {
                case 'cancel':
                    $resi->where('id', $id)->update([
                        'reserve_status' => -1
                    ]);

                    $res_type   = 'reserve';
                    $res_id     = $id;
                    $event_type = $event;
                    $detail     = [
                        'description' => $this->auth->nickname . '作废预订单, 理由:' . $remarks
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $reserve_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-linkman':
                    $realname    = input('realname', '');
                    $pinyinArray = $py->convert($realname);
                    $pinyin      = '';
                    $sname       = '';
                    foreach ($pinyinArray as $item) {
                        $pinyin .= $item;
                        $sname  .= ucwords(substr($item, 0, 1));
                    }

                    $resi->where('id', $id)->update([
                        'source'            => input('source', ''),
                        'sex'               => input('sex', 0),
                        'realname'          => $realname,
                        'pinyin'            => $pinyin,
                        'sname'             => $sname,
                        'certificates_type' => input('certificates_type', ''),
                        'person_no'         => input('person_no', ''),
                        'birthday'          => strtotime(input('birthday', 0)),
                        'nation'            => input('nation', ''),
                        'tel'               => input('tel', ''),
                        'remarks'           => input('reserve_remarks', '')
                    ]);

                    $this->pri_add_user($realname, input('sex', 0), strtotime(input('birthday', 0)), input('tel', ''), input('certificates_type', ''), input('person_no', ''));

                    $res_type   = 'reserve';
                    $res_id     = $id;
                    $event_type = $event;
                    $detail     = [
                        'description' => $this->auth->nickname . '修改患者信息, 理由:' . $remarks,
                        'old'         => [
                            'source'            => $m['source'],
                            'sex'               => $m['sex'],
                            'realname'          => $m['realname'],
                            'certificates_type' => $m['certificates_type'],
                            'person_no'         => $m['person_no'],
                            'birthday'          => $m['birthday'],
                            'tel'               => $m['tel'],
                            'remarks'           => $m['remarks']
                        ],
                        'new'         => [
                            'source'            => input('source', ''),
                            'sex'               => input('sex', 0),
                            'realname'          => input('realname', ''),
                            'certificates_type' => input('certificates_type', ''),
                            'person_no'         => input('person_no', ''),
                            'birthday'          => input('birthday', 0),
                            'tel'               => input('tel', ''),
                            'remarks'           => input('reserve_remarks', '')
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $reserve_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-date':
                    $check_in_time      = input('check_in_time', 0);
                    $check_in_time_int  = strtotime(date('Y-m-d', strtotime($check_in_time)));
                    $check_out_time     = input('check_out_time', 0);
                    $check_out_time_int = strtotime(date('Y-m-d', strtotime($check_out_time)));;

                    if (!($check_in_time_int && $check_out_time_int) || $check_in_time_int > $check_out_time_int) {
                        $this->error('时间格式不正确');
                    }
                    $days = (int)abs(($check_out_time_int - $check_in_time_int) / 86400);

                    $reserveDates = [];
                    $oiModel      = $oi->field('id,check_in_time,check_out_time')
                        ->where('room_info_id', $m['room_info_id'])
                        ->where("order_status", 0)
                        ->find();
                    if ($oiModel) {
                        $res_check_in_time  = date('Y-m-d', $oiModel['check_in_time']);
                        $res_check_out_time = date('Y-m-d', strtotime('-1 day', $oiModel['check_out_time']));
                        for ($i = 0; $i < 9999999; $i++) {
                            $reserveDateTemp = date('Y-m-d', strtotime(' + ' . $i . ' day', strtotime($res_check_in_time)));
                            array_push($reserveDates, $reserveDateTemp);
                            if ($reserveDateTemp == $res_check_out_time) {
                                break;
                            }
                        }
                    }

                    $resiList = $resi->field('id,check_in_time,check_out_time')
                        ->where('room_info_id', $m['room_info_id'])
                        ->where("reserve_status", 0)
                        ->where('id <> ' . $m['id'])
                        ->select();

                    foreach ($resiList as $item) {
                        $res_check_in_time  = date('Y-m-d', $item['check_in_time']);
                        $res_check_out_time = date('Y-m-d', strtotime('-1 day', $item['check_out_time']));
                        for ($i = 0; $i < 9999999; $i++) {
                            $reserveDateTemp = date('Y-m-d', strtotime(' + ' . $i . ' day', strtotime($res_check_in_time)));
                            array_push($reserveDates, $reserveDateTemp);
                            if ($reserveDateTemp == $res_check_out_time) {
                                break;
                            }
                        }
                    }

                    if (count($reserveDates)) {
                        $is_DateConflict = false;
                        for ($i = 0; $i < 9999999; $i++) {
                            $TempDate = date('Y-m-d', strtotime(' + ' . $i . ' day', $check_in_time_int));
                            if (in_array($TempDate, $reserveDates)) {
                                $is_DateConflict = true;
                                break;
                            }
                            if ($TempDate == date('Y-m-d', strtotime('-1 day', $check_out_time_int))) {
                                break;
                            }
                        }
                        if ($is_DateConflict) {
                            $this->error('日期有冲突');
                        }
                    }

                    $total_price = 0;
                    $price_json  = $ri->get_room_price_list($prefix, $m['room_info_id'], $check_in_time, date('Y-m-d', strtotime('-1 day', $check_out_time_int)));

                    foreach ($price_json as $item) {
                        $total_price += $item['price'];
                    }

                    $resi->where('id', $id)->update([
                        'check_in_time'  => strtotime($check_in_time),
                        'check_out_time' => strtotime($check_out_time),
                        'days'           => $days,
                        'price_json'     => json_encode($price_json),
                        'total_price'    => $total_price
                    ]);

                    $res_type = 'reserve';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '修改入住信息, 理由:' . $remarks,
                        'old'         => [
                            'check_in_time'  => date('Y-m-d H:i:s', $m['check_in_time']),
                            'check_out_time' => date('Y-m-d H:i:s', $m['check_out_time']),
                            'days'           => $m['days'],
                            'price_json'     => json_decode($m['price_json'], true),
                            'total_price'    => $m['total_price']
                        ],
                        'new'         => [
                            'check_in_time'  => $check_in_time,
                            'check_out_time' => $check_out_time,
                            'days'           => $days,
                            'price_json'     => $price_json,
                            'total_price'    => $total_price
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $reserve_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-addons':
                    $resi->where('id', $id)->update([
                        'addons' => input('addons', '')
                    ]);

                    $res_type = 'reserve';
                    $res_id   = $id;
                    $detail   = [
                        'description' => $this->auth->nickname . '修改附件, 理由:' . $remarks,
                        'old'         => [
                            'addons' => $m['addons']
                        ],
                        'new'         => [
                            'addons' => input('addons', '')
                        ]
                    ];
                    $el->insert([
                        'res_type'   => $res_type,
                        'res_id'     => $res_id,
                        'res_no'     => $reserve_no,
                        'event_type' => $event,
                        'detail'     => json_encode($detail),
                        'state'      => 0,
                        'createtime' => time(),
                        'creator'    => $this->auth->id
                    ]);
                    $this->success();
                    break;

                case 'edit-customer':
                    $customerJson = [];
                    if (input('customer_data', '')) {
                        $customer_dataJson = json_decode(input('customer_data', ''), true);
                        foreach ($customer_dataJson as $item) {
                            $pinyinArray = $py->convert($item['realname']);
                            $pinyin      = '';
                            $sname       = '';
                            foreach ($pinyinArray as $x) {
                                $pinyin .= $x;
                                $sname  .= ucwords(substr($x, 0, 1));
                            }

                            array_push($customerJson, [
                                'user_id'           => 0,
                                'realname'          => $item['realname'],
                                'sname'             => $sname,
                                'pinyin'            => $pinyin,
                                'sex'               => $item['sex'],
                                'certificates_type' => $item['certificates_type'],
                                'person_no'         => $item['person_no'],
                                'birthday'          => strtotime($item['birthday']),
                                'tel'               => $item['tel']
                            ]);
                        }
                    }


                    $rplList = $rpl->field('user_id,realname,sname,pinyin,sex,certificates_type,person_no,birthday,tel')->where('reserve_id', $id)->where('state', 0)->select();

                    if (count($customerJson) > 0) {
                        $rpl->where('reserve_id', $id)->update([
                            'state' => -1
                        ]);
                        foreach ($customerJson as $item) {
                            $rpl->insert([
                                'reserve_id'        => $m['id'],
                                'user_id'           => $item['user_id'],
                                'realname'          => $item['realname'],
                                'sname'             => $item['sname'],
                                'pinyin'            => $item['pinyin'],
                                'sex'               => $item['sex'],
                                'certificates_type' => $item['certificates_type'],
                                'person_no'         => $item['person_no'],
                                'birthday'          => $item['birthday'],
                                'tel'               => $item['tel'],
                                'remarks'           => '',
                                'state'             => 0,
                                'createtime'        => time(),
                                'creator'           => $this->auth->id,
                                'updatetime'        => time(),
                                'last_editor'       => $this->auth->id
                            ]);

                            $this->pri_add_user($item['realname'], $item['sex'], $item['birthday'], $item['tel'], $item['certificates_type'], $item['person_no']);
                        }

                        $res_type = 'reserve';
                        $res_id   = $id;
                        $detail   = [
                            'description' => $this->auth->nickname . '修改同住客人, 理由:' . $remarks,
                            'old'         => [
                                'list' => $rplList
                            ],
                            'new'         => [
                                'list' => $customerJson
                            ]
                        ];
                        $el->insert([
                            'res_type'   => $res_type,
                            'res_id'     => $res_id,
                            'res_no'     => $reserve_no,
                            'event_type' => $event,
                            'detail'     => json_encode($detail),
                            'state'      => 0,
                            'createtime' => time(),
                            'creator'    => $this->auth->id
                        ]);
                    }
                    $this->success();
                    break;
            }
        } else {
            $this->error('预订单不存在');
        }
    }

    /**
     * Ajax预定转入订单操作
     */
    public function ajax_change_into_order()
    {
        $conf       = new \app\admin\model\Pmsconfig;
        $resi       = new \app\admin\model\Pmsreserveinfo;
        $oi         = new \app\admin\model\Pmsorderinfo;
        $ri         = new \app\admin\model\Pmsroominfo;
        $order_flag = $conf->getvalue('order_flag');
        $prefix     = $this->prefix;

        $id = input('id', 0);

        if ($id) {
            $m = $resi->alias('resi')
                ->field('resi .*,ri . room_status')
                ->join($prefix . 'pms_room_info ri', 'ri . id = resi . room_info_id')
                ->where('resi . id', $id)->where('resi . reserve_status', 0)->find();
            if ($m) {
                if ($m['room_status'] == 0) {
                    if (date('Y-m-d', $m['check_in_time']) == date('Y-m-d')) {
                        $order_id = $oi->insertGetId([
                            'reserve_id'        => $m['id'],
                            'order_no'          => $oi->create_order_no($order_flag),
                            'source'            => $m['source'],
                            'realname'          => $m['realname'],
                            'sname'             => $m['sname'],
                            'pinyin'            => $m['pinyin'],
                            'certificates_type' => $m['certificates_type'],
                            'person_no'         => $m['person_no'],
                            'sex'               => $m['sex'],
                            'nation'            => $m['nation'],
                            'birthday'          => $m['birthday'],
                            'tel'               => $m['tel'],
                            'check_in_time'     => $m['check_in_time'],
                            'check_out_time'    => $m['check_out_time'],
                            'days'              => $m['days'],
                            'room_type_id'      => $m['room_type_id'],
                            'room_info_id'      => $m['room_info_id'],
                            'is_hour_room'      => 0,
                            'remarks'           => $m['remarks'],
                            'order_status'      => -1,
                            'total_price'       => $m['total_price'],
                            'gmv'               => $m['total_price'],
                            'deposit'           => $m['deposit'],
                            'addons'            => $m['addons'],
                            'price_json'        => $m['price_json'],
                            'createtime'        => time(),
                            'creator'           => $this->auth->id,
                            'updatetime'        => time(),
                            'last_editor'       => $this->auth->id
                        ]);

                        $oi->query('insert into ' . $prefix . 'pms_order_people_list(order_id, user_id, realname, sname, pinyin, sex, certificates_type, person_no, birthday, tel, remarks, state, createtime, creator, updatetime, last_editor) select ' . $order_id . ',0,realname,sname,pinyin,sex,certificates_type,person_no,birthday,tel,remarks,state,UNIX_TIMESTAMP(now()),' . $this->auth->id . ',UNIX_TIMESTAMP(now()),' . $this->auth->id . ' from ' . $prefix . 'pms_reserve_people_list where reserve_id = ' . $m['id']);

                        $resi->where('id', $id)->update(['reserve_status' => 1]);
                        $ri->where('id', $m['room_info_id'])->update(['room_status' => 1]);

                        $this->success();
                    } else {
                        $this->error('预定入住日期与当前日期不符，不能办理预定转入');
                    }
                } else {
                    $this->error('当前房间有人入住，不能办理预定转入');
                }
            } else {
                $this->error('读取预定错误');
            }
        }
    }



    //////////////////////////////////////////////////


    //添加会员记录
    private function pri_add_user($realname, $sex, $birthday, $tel, $certificates_type, $person_no)
    {
        $u   = new \app\admin\model\Pmsuser;
        $opl = new \app\admin\model\Pmsorderpeoplelist;
        $py  = new Pinyin();

        $m = $u->field('id')->where('realname', $realname)->where('certificates_type', $certificates_type)->where('person_no', $person_no)->where('state', 0)->find();

        if (!$m) {
            $pinyinArray = $py->convert($realname);
            $pinyin      = '';
            $sname       = '';
            foreach ($pinyinArray as $item) {
                $pinyin .= $item;
                $sname  .= ucwords(substr($item, 0, 1));
            }

            $id = $u->insertGetId([
                'realname'          => $realname,
                'sname'             => $sname,
                'pinyin'            => $pinyin,
                'sex'               => $sex,
                'certificates_type' => $certificates_type,
                'person_no'         => $person_no,
                'birthday'          => $birthday,
                'tel'               => $tel,
                'check_in_count'    => 1,
                'remarks'           => '',
                'state'             => 0,
                'createtime'        => time(),
                'creator'           => $this->auth->id,
                'updatetime'        => time(),
                'last_editor'       => $this->auth->id
            ]);
        } else {
            $id = $m['id'];
        }

        //更新入住次数
        $check_in_count = $opl->field('id')->where('realname', $realname)->where('certificates_type', $certificates_type)->where('person_no', $person_no)->where('state', 0)->count();

        $u->where('id', $id)->update(['check_in_count' => $check_in_count]);
    }

    //计算销售额，包括房费、房间物品消费、服务消费综合
    private function pri_get_gmv($order_id)
    {
        $oi             = new \app\admin\model\Pmsorderinfo;
        $oroomitems     = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems = new \app\admin\model\Pmsorderservicesitems;

        $gmv = 0;
        if ($order_id) {
            $oiModel = $oi->where('id', $order_id)->find();
            $gmv     += $oiModel['total_price'];

            $oroomitemsList = $oroomitems->where('order_id', $order_id)->select();
            if (count($oroomitemsList)) {
                foreach ($oroomitemsList as $item) {
                    $gmv += $item['price'] * $item['num'];
                }
            }

            $oservicesitemsList = $oservicesitems->where('order_id', $order_id)->select();
            if (count($oservicesitemsList)) {
                foreach ($oservicesitemsList as $item) {
                    $gmv += $item['price'] * $item['num'];
                }
            }

            $oi->where('id', $order_id)->update([
                'gmv' => $gmv
            ]);
        }
    }
}
